﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using QSASPMVCApplicationCSharp.Models;
using QSASPMVCApplicationCSharp.Models.Binders;
using QSASPMVCApplicationCSharp.Data;
using ValidationFramework.Fluent;
using ValidationFramework;

namespace QSASPMVCApplicationCSharp
{
	public class GlobalApplication : HttpApplication
	{

		// Application Events
		protected void Application_Start(object sender, EventArgs e)
		{
			RegisterValidation();
			RegisterBinders();
			RegisterRoutes(RouteTable.Routes);
		}
		protected void Session_Start(object sender, EventArgs e)
		{
			InitializeRepositories();
		}

		// Routing
		public static void RegisterRoutes(RouteCollection routes)
		{
			// Note: Change the URL to "{controller}.mvc/{action}/{id}" to enable
			//       automatic support on IIS6 and IIS7 classic mode

			routes.MapRoute(
							"Default",                                              // Route name
							"{controller}/{action}/{id}",                           // URL with parameters
							new { controller = "Product", action = "Browse", id = "" }  // Parameter defaults
						);
		}
		
		// Validation
		private static void RegisterValidation()
		{
			Validation.Ensure<Product>(x => x.ProductName).Passes(new RequiredStringRule());
			Validation.Ensure<Product>(x => x.ProductName).Passes(new CustomRule("{0} is invalid", false, CustomValidationMethods.RequireUniqueProductId, "A Product with that name already exists"));
		}

		// Binder
		private static void RegisterBinders()
		{
			ModelBinders.Binders[typeof(Product)] = new ProductBinder();
		}

		// Repository
		private static void InitializeRepositories()
		{
			InitProductRepository();
		}
		private static void InitProductRepository()
		{
			var repo = new SessionProductRepository();
			for (var i = 0; i < 10; i++)
			{
				var id = i + 1; // convert to 1 index
				var product = new Product()
				{
					ProductId = id,
					Discontinued = false,
					ProductName = string.Format("Product{0}", id),
					UnitPrice = id * 10,
					ReorderLevel = id * 100
				};
				repo.SaveProduct(product);
			}
		}
	}
}